/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.hiddendanger.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.audit.mapper.AuditMapper;
import com.koron.common.bean.*;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.stub.Port;
import com.koron.common.util.DocConverterUtils;
import com.koron.common.web.Util;
import com.koron.hazardsource.domain.IndicationItems;
import com.koron.hazardsource.mapper.IndicationItemsMapper;
import com.koron.hazardsource.service.api.IndicationItemsService;
import com.koron.hazardsource.util.Immutable;
import com.koron.hiddendanger.domain.CheckRecord;
import com.koron.hiddendanger.domain.HiddenDangerDiscovery;
import com.koron.hiddendanger.domain.HiddenDangerRectification;
import com.koron.hiddendanger.mapper.CheckMapper;
import com.koron.hiddendanger.mapper.CheckRecordMapper;
import com.koron.hiddendanger.mapper.HiddenDangerMapper;
import com.koron.hiddendanger.mapper.HiddenDangerRectificationMapper;
import com.koron.hiddendanger.service.api.HiddenDangerDiscoveryService;
import com.koron.hiddendanger.uitls.BusinessCode;
import com.koron.hiddendanger.uitls.OverdueJudgmentUtil;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.mapper.CorpManagementMapper;
import com.koron.system.domain.DictData;
import com.koron.system.domain.Message;
import com.koron.system.mapper.MessageMapper;
import com.koron.system.service.api.DictDataService;
import com.koron.workflow.bean.MessageEntity;
import com.koron.workflow.service.api.WorkflowService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.koron.ebs.mybatis.SessionFactory;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.InputStream;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class HiddenDangerDiscoveryServiceImpl implements HiddenDangerDiscoveryService, AfterApprovalService, InitializingBean {

    private final static  Logger logger = LoggerFactory.getLogger(HiddenDangerDiscoveryServiceImpl.class);

    @Value("${app.orgCode}")
    private String orgCode;

    @Value("${app.appid}")
    private String appid;

    @Value("${app.secret}")
    private String secret;

    /**
     * 系统管理员角色code
     */
    @Value("${app.managerRole}")
    private String systemAdministratorCode;

    @Value("${risk_danger_setCode}")
    private String riskDangerSetCode;

    private final SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");


    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Autowired
    private Util util;

    @Autowired
    private IndicationItemsService indicationItemsService;

    @Autowired
    private DictDataService dataService;

    // @Autowired默认按照byType 注入，也就是bean的类型的来传入,
    // 如果需要指定名字，那么需要使@Qualifier("这是bean的名字")
    @Autowired
    private Scheduler scheduler;

    @Autowired
    private WorkflowService flowService;

    @Value("${danger_work_flow}")
    private String hiddenDangerWorkFlow;

    @Override
    public MessageBean<Integer> saveOrCommit(StaffBean user, HiddenDangerDiscovery dangerDiscovery, Integer operationType,
                                             String delAtts, String keepAtts, MultipartFile[] files, String title, String note, String approval) {
        MessageBean<Integer> msg = new MessageBean<>();
        List<String> newAtts = new ArrayList<>();
        SessionFactory factory = new SessionFactory();
        try {
            if (null == operationType) {
                msg.setCode(BusinessCode.DANGER_EMPTY_OPERATIONTYPE.getCode());
                msg.setDescription(BusinessCode.DANGER_EMPTY_OPERATIONTYPE.getDescription());
                return msg;
            }
            if (0 != operationType && 1 != operationType) {
                msg.setCode(BusinessCode.DANGER_ILEAGEL_OPERATIONTYPE.getCode());
                msg.setDescription(BusinessCode.DANGER_ILEAGEL_OPERATIONTYPE.getDescription());
                return msg;
            }
            msg = checkDanger(dangerDiscovery);
            if (msg.getCode() != BusinessCode.SUCCESS.getCode()) {
                return msg;
            }
            if (null != files && files.length > 0) {
                for (MultipartFile file : files) {
                    String fileName = file.getOriginalFilename();
                    //获取文件后缀名
                    String substring = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    //判断是否属于图片
                    boolean contains = Lists.newArrayList("bmp", "gif", "jpg", "psd", "tiff", "eps", "tga", "jpeg", "png").contains(substring);
                    if (!contains) {
                        msg.setCode(BusinessCode.FAILURE.getCode());
                        msg.setDescription(fileName + "不是图片，请上传图片");
                        return msg;
                    }
                    String url = clientWrapper.uploadFile(file);
                    newAtts.add(url + "#" + file.getOriginalFilename());
                }
            }
            if (StringUtils.isNotEmpty(dangerDiscovery.getCheckRecordId())) {
                if (dangerDiscovery.getDerivation() == 1) {
                    CheckRecord checkRecord = factory.getMapper(CheckRecordMapper.class).queryOne(dangerDiscovery.getCheckRecordId());
                    if (null != checkRecord && checkRecord.getSubmit() == 0) {
                        dangerDiscovery.setState(7);
                    } else {
                        dangerDiscovery.setState(0);
                    }
                } else if (dangerDiscovery.getDerivation() == 4) {
                    Map deviceCheck = factory.getMapper(CheckMapper.class).queryDeviceCheck(dangerDiscovery.getCheckRecordId());
                    if (null != deviceCheck && !deviceCheck.isEmpty() && "1".equals(deviceCheck.get("status").toString())) {
                        dangerDiscovery.setState(7);
                    } else {
                        dangerDiscovery.setState(0);
                    }
                } else if (dangerDiscovery.getDerivation() == 5) {
                    Map materialCheckRecord = factory.getMapper(CheckMapper.class).queryMaterialCheck(dangerDiscovery.getCheckRecordId());
                    if (null != materialCheckRecord && materialCheckRecord.isEmpty() && "1".equals(materialCheckRecord.get("status"))) {
                        dangerDiscovery.setState(7);
                    } else {
                        dangerDiscovery.setState(0);
                    }
                } else {
                    dangerDiscovery.setState(0);
                }
            } else {
                dangerDiscovery.setState(0);
            }
            Audit audit = null;
            String userid = "";
            if (operationType == 1) {
                //提交隐患
                if (StringUtils.isEmpty(dangerDiscovery.getDangerManager())) {
                    msg.setCode(BusinessCode.DANGER_ILEAGEL_OPERATIONTYPE.getCode());
                    msg.setDescription("隐患负责人不能为空");
                    return msg;
                }
                approval = dangerDiscovery.getDangerManager();
                if (approval.split("_").length > 1) {
                    userid = approval.split("_")[1];
                } else {
                    List<StaffBean> list = (List<StaffBean>) util.staff(approval.split("_")[0], null).getData();
                    if (null != list && list.size() > 0) {
                        userid = list.get(0).getUserid();
                    }
                    dangerDiscovery.setDangerManager(StringUtils.join(approval, "_", userid));
                }
                dangerDiscovery.setState(2);
                audit = new Audit();
                audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                audit.setUpdateUser(dangerDiscovery.getUpdateUser());
                audit.setUpdateTime(dangerDiscovery.getUpdateTime());
                audit.setAddTime(dangerDiscovery.getUpdateTime());
                audit.setAddUser(dangerDiscovery.getUpdateUser());
                audit.setFlowType(2);
                audit.setFlowName(Immutable.HIDDENDANGER_WORKFLOW);
                audit.setNowNodeCode("Process-task2");
                audit.setTarget(HiddenDangerDiscoveryServiceImpl.class.getName());
                audit.setOperation(1);
                audit.setTitle(StringUtils.isEmpty(title) ? "隐患整改流程" : title);
                audit.setCorpCode(dangerDiscovery.getCorpCode());
                audit.setBusinessIds(dangerDiscovery.getId());
                audit.setInitiatorCode(dangerDiscovery.getSubmitterCode());
                audit.setNextGridNode(dangerDiscovery.getGridCode());
                audit.setDescription(StringUtils.isEmpty(note) ? "隐患整改流程" : note);
                audit.setState(1);
                audit.setTemplateKey(hiddenDangerWorkFlow);
                audit.setInitiatorAccount(user.getUserid());
                audit.setSetCode(riskDangerSetCode);
            }
            if (StringUtils.isEmpty(dangerDiscovery.getId())) {
                // 新增
                dangerDiscovery.setId(DefaultIdGenerator.getInstance().generateLongId());
                dangerDiscovery.setCode(generateCode(factory, dangerDiscovery));
                dangerDiscovery.setAddTime(dangerDiscovery.getUpdateTime());
                dangerDiscovery.setAddUser(dangerDiscovery.getUpdateUser());
                if (StringUtils.isBlank(dangerDiscovery.getCheckRecordId()) && StringUtils.isBlank(dangerDiscovery.getFreeSnapId())) {
                    dangerDiscovery.setDerivation(3);
                }
                Port port = getPort();
                List<DeptBean> departmentTreeBeanList = port.dept(user.getCode()).getData();
                dangerDiscovery.setSubmitterDepartment(departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0 ? null : departmentTreeBeanList.get(0).getCode());
                MessageBean<?> corpMsg = util.corp(user.getCode());
                if (corpMsg.getCode() == 0 && null != corpMsg.getData()) {
                    DepartmentTreeBean corp = (DepartmentTreeBean) corpMsg.getData();
                    dangerDiscovery.setCheckUnit(corp.getDepartmentCode());
                    dangerDiscovery.setCheckUnitName(corp.getName());
                }
                if (null != newAtts && newAtts.size() > 0) {
                    dangerDiscovery.setAttachment(new Gson().toJson(newAtts));
                }
                if (StringUtils.isEmpty(dangerDiscovery.getDeviceCode())) {
                    dangerDiscovery.setDeviceCode("LSHDD-" + dangerDiscovery.getId().substring(dangerDiscovery.getId().length() - 6));
                }
                factory.getMapper(HiddenDangerMapper.class).insertDanger(dangerDiscovery);
            } else {
                //修改
                //先判断是否已经提交过了
                HiddenDangerDiscovery entity = queryDangerOne(dangerDiscovery.getId()).getData();
                if (null == entity) {
                    msg.setCode(BusinessCode.DANGER_NOT_EXISIT.getCode());
                    msg.setDescription(BusinessCode.DANGER_NOT_EXISIT.getDescription());
                    return msg;
                }
                if (entity.getState() != 0 && entity.getState() != 7) {
                    msg.setCode(BusinessCode.DANGER_IS_COMMITED.getCode());
                    msg.setDescription(BusinessCode.DANGER_IS_COMMITED.getDescription());
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getCheckUnit()) && StringUtils.isEmpty(dangerDiscovery.getCheckUnitName())) {
                    if (StringUtils.isEmpty(entity.getCheckUnit()) && StringUtils.isEmpty(entity.getCheckUnitName())) {
                        MessageBean<?> corpMsg = util.corp(user.getCode());
                        if (corpMsg.getCode() == 0 && null != corpMsg.getData()) {
                            DepartmentTreeBean corp = (DepartmentTreeBean) corpMsg.getData();
                            dangerDiscovery.setCheckUnit(corp.getDepartmentCode());
                            dangerDiscovery.setCheckUnitName(corp.getName());
                        }
                    } else {
                        dangerDiscovery.setCheckUnit(entity.getCheckUnit());
                        dangerDiscovery.setCheckUnitName(entity.getCheckUnitName());
                    }
                }
                List<String> keepAttsList = new ArrayList<>();
                if (null != newAtts && newAtts.size() > 0) {
                    keepAttsList.addAll(newAtts);
                }
                if (StringUtils.isNotEmpty(keepAtts)) {
                    String[] keepAttsArray = keepAtts.split("[，,]");
                    for (String att : keepAttsArray) {
                        keepAttsList.add(att);
                    }
                }
                if (null != keepAttsList && keepAttsList.size() > 0) {
                    dangerDiscovery.setAttachment(new Gson().toJson(keepAttsList));
                }
                if (StringUtils.isEmpty(dangerDiscovery.getDeviceCode())) {
                    dangerDiscovery.setDeviceCode("LSHDD-" + dangerDiscovery.getId().substring(dangerDiscovery.getId().length() - 8));
                }
                if (StringUtils.isEmpty(dangerDiscovery.getLegalBasis()) || ("null").equals(dangerDiscovery.getLegalBasis())) {
                    dangerDiscovery.setLegalBasis("");
                }
                if (StringUtils.isEmpty(dangerDiscovery.getLocation()) || ("null").equals(dangerDiscovery.getLocation())) {
                    dangerDiscovery.setLocation("");
                }
                Integer value = factory.getMapper(HiddenDangerMapper.class).updateDanger(dangerDiscovery);
                if (value > 0) {
                    if (StringUtils.isNotEmpty(delAtts)) {
                        String[] delAttsArray = delAtts.split("[，,]");
                        for (String att : delAttsArray) {
                            clientWrapper.deleteFile(att.split("#")[0]);
                        }
                    }
                }
            }
            if (null != audit) {
                List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(approval.split("_")[0], null).getData();
                List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(approval.split("_")[0]).getData();
                if (staffBeanList.size() <= 0 || null == staffBeanList || null == deptBeanList || deptBeanList.size() <= 0) {
                    factory.close(false);
                    msg.setCode(BusinessCode.DANGER_ILEAGEL_OPERATIONTYPE.getCode());
                    msg.setDescription("提交时隐患确认人不存在，无法提交");
                    return msg;
                }
                //保存隐患整改信息，主要是配置隐患整改信息的验证人
                HiddenDangerRectification rectification = new HiddenDangerRectification();
                //保存整改信息
                rectification.setHiddenDangerId(dangerDiscovery.getId());
                rectification.setId(DefaultIdGenerator.getInstance().generateLongId());
                rectification.setAddTime(dangerDiscovery.getUpdateTime());
                rectification.setAddUser(user.getName());
                rectification.setUpdateTime(dangerDiscovery.getUpdateTime());
                rectification.setUpdateUser(user.getName());
                rectification.setReviewer(approval.split("_")[0]);
                rectification.setRectifier(dangerDiscovery.getDangerManager());
                rectification.setRectifierName(dangerDiscovery.getDangerManagerName());
                rectification.setDeadline(dangerDiscovery.getRectificationPeriod());
                rectification.setSolution(dangerDiscovery.getHandlingOpinions());
                rectification.setReviewerName(staffBeanList.get(0).getName() + "_" + deptBeanList.get(0).getName());
                rectification.setDelayState(0);
                IndicationItems items = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "未整改");
                rectification.setRectificationState(items == null ? null : items.getId());
                factory.getMapper(HiddenDangerMapper.class).insertRectification(rectification);
                List<String> idList = new ArrayList<>();
                idList.add(dangerDiscovery.getId());
                audit.setBusinessIds(new Gson().toJson(idList));
                Map<String, Object> businessDataMap = new HashMap<>();
//                businessDataMap.put("approval", userid);
                businessDataMap.put("rectifier", userid);
                businessDataMap.put("reviewer", userid);
                businessDataMap.put("verification", user.getUserid());
                if (!flowManagement.initFlow(user, audit, businessDataMap)) {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("隐患整改流程启动失败");
                    return msg;
                } else {
                    // 隐患提交，流程启动成功后，生成隐患整改通知书
                    List<HiddenDangerDiscovery> list = new ArrayList<>();
                    list.add(dangerDiscovery);
                    HiddenDangerRectificationServiceImpl.generateHiddenDangerRectificationNotice(factory, user, list);
                    factory.close();
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription("隐患整改流程启动成功");
                    return msg;
                }
            } else {
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("隐患保存成功");
                msg.setData(1);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<Integer> startDangerWorkFlow(StaffBean user, String corpCode, String title, String note, String approval, String[] hiddenDangerIds) {
        SessionFactory factory = null;
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Integer.class);
        try {
            factory = new SessionFactory();
            //先判断选中的隐患是否都是草稿状态
            List<String> idList = new ArrayList<>();
            if (null == hiddenDangerIds || hiddenDangerIds.length <= 0) {
                msg.setCode(BusinessCode.PARAM_NOT_EMPTY.getCode());
                msg.setDescription("未选中数据");
                return msg;
            }
            HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
            List<HiddenDangerDiscovery> hiddenDangerDiscoveryList = mapper.queryDangerByIdList(Arrays.asList(hiddenDangerIds));
            int count = 0;
            int flag = 1;
            for (HiddenDangerDiscovery discovery : hiddenDangerDiscoveryList) {
                //验证提交的数据必填项是否完整，主要针对导入图片的草稿数据
                if (!checkHiddenDangerDiscovery(discovery)) {
                    msg.setCode(BusinessCode.PARAM_NOT_EMPTY.getCode());
                    msg.setDescription("选中提交的数据中，第" + flag + "条的隐患数据必填信息不完整，请补充完整后再提交！");
                    return msg;
                }
                if (discovery.getState() != 0) {
                    count++;
                }
                if (StringUtils.isEmpty(approval)) {
                    approval = discovery.getDangerManager();
                }
                if (StringUtils.isNotEmpty(approval)) {
                    if (!approval.equals(discovery.getDangerManager())) {
                        msg.setCode(BusinessCode.PARAM_NOT_EMPTY.getCode());
                        msg.setDescription("只有隐患负责人为同一个人时，才能批量提交");
                        return msg;
                    }
                }
                flag++;
            }
            if (count > 0) {
                msg.setCode(BusinessCode.DANGER_IS_COMMITED.getCode());
                msg.setDescription("选中的数据包含已经提交即非草稿状态的数据，无法执行提交操作");
                return msg;
            }
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(approval.split("_")[0], null).getData();
            List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(approval.split("_")[0]).getData();
            if (staffBeanList.size() <= 0 || null == staffBeanList || null == deptBeanList || deptBeanList.size() <= 0) {
                msg.setCode(BusinessCode.DANGER_ILEAGEL_OPERATIONTYPE.getCode());
                msg.setDescription("提交时隐患确认人不存在，无法提交");
                return msg;
            }
            //整理隐患整改记录
            List<HiddenDangerRectification> rectificationList = new ArrayList<>();
            List<HiddenDangerRectification> deleteList = new ArrayList<>();
            for (HiddenDangerDiscovery dangerDiscovery : hiddenDangerDiscoveryList) {
                //查询提交的隐患是不是已经有了整改记录；
                List<HiddenDangerRectification> rectificationList1 = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(dangerDiscovery.getId());
                //删除之前有的整改记录信息
                if (rectificationList1 != null && rectificationList1.size() > 0) {
                    deleteList.addAll(rectificationList1);
                }
                //保存隐患整改信息，主要是配置隐患整改信息的验证人
                HiddenDangerRectification rectification = new HiddenDangerRectification();
                //保存整改信息
                rectification.setHiddenDangerId(dangerDiscovery.getId());
                rectification.setId(DefaultIdGenerator.getInstance().generateLongId());
                rectification.setAddTime(dangerDiscovery.getUpdateTime());
                rectification.setAddUser(user.getName());
                rectification.setUpdateTime(dangerDiscovery.getUpdateTime());
                rectification.setUpdateUser(user.getName());
                rectification.setRectifier(dangerDiscovery.getDangerManager());
                rectification.setRectifierName(dangerDiscovery.getDangerManagerName());
                rectification.setDeadline(dangerDiscovery.getRectificationPeriod());
                rectification.setSolution(dangerDiscovery.getDescription());
                rectification.setReviewer(approval.split("_")[0]);
                rectification.setReviewerName(staffBeanList.get(0).getName() + "_" + deptBeanList.get(0).getName());
                rectification.setDelayState(0);
                IndicationItems items = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "未整改");
                rectification.setRectificationState(items == null ? null : items.getId());
                rectificationList.add(rectification);
            }
            //更新选中的隐患为确认状态；启动隐患流程
            mapper.updateDangerState(2, Arrays.asList(hiddenDangerIds));
            try {
                for (HiddenDangerDiscovery discovery : hiddenDangerDiscoveryList) {
                    List<Message> messages = new ArrayList<>();
                    if (discovery.getCopyPerson() != null) {
                        String[] copyPersons = discovery.getCopyPerson().split(",");
                        for (String copyPerson : copyPersons) {
                            Message message = new Message();
                            message.setId(DefaultIdGenerator.getInstance().generateLongId());
                            message.setTitle("有一项您关注的隐患整改");
                            message.setIsRead(0);
                            message.setIsRemove(0);
                            message.setAddTime(new Date());
                            message.setAddUser(discovery.getAddUser());
                            message.setContent("隐患描述：" + discovery.getDescription());
                            message.setReceiverCode(copyPerson.split("_")[0]);
                            messages.add(message);
                        }
                    }
                    if (messages != null && messages.size() > 0) {
                        factory.getMapper(MessageMapper.class).batchInsert(messages);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
            mapper.batchInsertRectification(rectificationList);
            if (deleteList != null && deleteList.size() > 0) {
                List<String> deleteIdList = deleteList.stream().map(HiddenDangerRectification::getId).collect(Collectors.toList());
                mapper.bateDeleteRectification(deleteIdList);
            }
            Date date = new Date();
            Audit audit = new Audit();
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setUpdateUser(user.getName());
            audit.setUpdateTime(date);
            audit.setAddTime(date);
            audit.setAddUser(user.getName());
            audit.setFlowType(2);
            audit.setOperation(1);
            audit.setTarget(HiddenDangerDiscoveryServiceImpl.class.getName());
            audit.setFlowName(Immutable.HIDDENDANGER_WORKFLOW);
            audit.setNowNodeCode("Process-task2");
            //audit.setTitle( rectification.getUpdateUser() + "提交了隐患的整改结果待验证");
            audit.setTitle(StringUtils.isEmpty(title) ? "隐患整改流程" : title);
            audit.setCorpCode(corpCode);
            audit.setBusinessIds(new Gson().toJson(Arrays.asList(hiddenDangerIds)));
            audit.setInitiatorCode(user.getCode());
            audit.setTemplateKey(hiddenDangerWorkFlow);
            audit.setInitiatorAccount(user.getUserid());
            audit.setSetCode(riskDangerSetCode);
            audit.setDescription(StringUtils.isEmpty(note) ? "隐患整改流程" : note);
            audit.setState(1);
            Map<String, Object> businessDataMap = new HashMap<>();
            String userid = "";
            if (approval.split("_").length > 1) {
                userid = approval.split("_")[1];
            } else {
                List<StaffBean> list = (List<StaffBean>) util.staff(approval.split("_")[0], null).getData();
                if (null != list && list.size() > 0) {
                    userid = list.get(0).getUserid();
                }
            }
//            businessDataMap.put("approval", userid);
            businessDataMap.put("rectifier", userid);
            businessDataMap.put("reviewer", userid);
            businessDataMap.put("verification", user.getUserid());
            if (!flowManagement.initFlow(user, audit, businessDataMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("隐患整改流程启动失败");
                return msg;
            } else {
                // 提交成功，生成整改通知书
                HiddenDangerRectificationServiceImpl.generateHiddenDangerRectificationNotice(factory, user, hiddenDangerDiscoveryList);
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("隐患整改流程启动成功");
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }


    private Boolean checkHiddenDangerDiscovery(HiddenDangerDiscovery dangerDiscovery) {
        //网格、隐患负责人、隐患分级、隐患分类、一级分类、二级分类、设备设施、隐患描述为空
        if (StringUtils.isEmpty(dangerDiscovery.getGridCode()) || StringUtils.isEmpty(dangerDiscovery.getDangerManager()) ||
                StringUtils.isEmpty(dangerDiscovery.getDescription())) {
            return false;
        }
        return true;
    }

    @Override
    public MessageBean<Integer> updateDangerRectification(StaffBean user, HiddenDangerRectification rectification, Integer operation, MultipartFile[] files, MultipartFile[] supervisionUnitFile, MultipartFile[] rectificationFile) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Integer.class);
        SessionFactory factory = null;
        List<String> keepAtts = new ArrayList<>();
        List<String> keepSupervisionUnitFiles = new ArrayList<>();
        List<String> keepFileAtts = new ArrayList<>();
        List<String> keepPreviewFileAtts = new ArrayList<>();
        try {
            factory = new SessionFactory();
            Date date = new Date();
            HiddenDangerMapper dangerMapper = factory.getMapper(HiddenDangerMapper.class);
            HiddenDangerDiscovery dangerDiscovery = factory.getMapper(HiddenDangerMapper.class).queryDangerOne(rectification.getHiddenDangerId());
            if (null == dangerDiscovery) {
                msg.setCode(BusinessCode.DANGER_NOT_EXISIT.getCode());
                msg.setDescription(BusinessCode.DANGER_NOT_EXISIT.getDescription());
                return msg;
            }
            List<IndicationItems> itemsList = new ArrayList<>();
            String hiddenDangerId = rectification.getHiddenDangerId();
            List<HiddenDangerRectification> rectificationList = dangerMapper.queryRectificationByDangerRecordId(hiddenDangerId);
            if (rectificationList == null || rectificationList.size() <= 0) {
                msg.setCode(BusinessCode.DANGER_NOT_EXISIT.getCode());
                msg.setDescription(BusinessCode.DANGER_NOT_EXISIT.getDescription());
                return msg;
            }
            switch (operation) {
                case 0:
                    rectification.setId(rectificationList.get(0).getId());
                    //确认隐患负责人、隐患整改期限、隐患整改措施
                    rectification.setUpdateTime(date);
                    rectification.setUpdateUser(user.getCode());
                    rectification.setUpdateUserName(user.getName());
                    IndicationItems itemsUn = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "未整改");
                    rectification.setRectificationState(itemsUn == null ? null : itemsUn.getId());
                    itemsUn.setReferenceCount(itemsUn.getReferenceCount() + 1);
                    itemsList.add(itemsUn);
                    if (null != rectification.getDeadline()) {
                        Date rectificationPeriod = dangerDiscovery.getRectificationPeriod();
                        if (null != rectificationPeriod && rectification.getDeadline().after(rectificationPeriod)) {
                            factory.close(false);
                            msg.setCode(BusinessCode.DEADLINE_AFTER_PERIOD.getCode());
                            msg.setDescription(BusinessCode.DEADLINE_AFTER_PERIOD.getDescription());
                            return msg;
                        }
                    }
                    dangerMapper.updateRectification(rectification);
                    //修改隐患流程为已确认整改人等信息
                    dangerDiscovery.setOperation(1);
                    dangerMapper.updateDanger(dangerDiscovery);
                    if (null != itemsList && itemsList.size() > 0) {
                        factory.getMapper(IndicationItemsMapper.class).batchUpdate(itemsList);
                    }
                    factory.close();
                    msg.setDescription("隐患确认信息成功");
                    return msg;
                case 1:
                    //填写隐患
                    rectification.setRectifier(rectificationList.get(0).getRectifier());
                    if (!user.getCode().equals(rectification.getRectifier().split("_")[0])) {
                        msg.setCode(BusinessCode.FAILURE.getCode());
                        msg.setDescription("无法保存，隐患整改负责人不是您，无法操作");
                        return msg;
                    }
                    if (null != files && files.length > 0) {
                        for (MultipartFile file : files) {
                            String fileName = file.getOriginalFilename();
                            //获取文件后缀名
                            String substring = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                            //判断是否属于图片
                            boolean contains = Lists.newArrayList("bmp", "gif", "jpg", "psd", "tiff", "eps", "tga", "jpeg", "png").contains(substring);
                            if (!contains) {
                                msg.setCode(BusinessCode.FAILURE.getCode());
                                msg.setDescription(fileName + "不是图片，请上传图片");
                                return msg;
                            }
                            String url = clientWrapper.uploadFile(file);
                            keepAtts.add(url + "#" + file.getOriginalFilename());
                        }
                        if (null != keepAtts && keepAtts.size() > 0) {
                            rectification.setRectificationAttachment(new Gson().toJson(keepAtts));
                        }
                    }
                    if (null != supervisionUnitFile && supervisionUnitFile.length > 0) {
                        for (MultipartFile file : supervisionUnitFile) {
                            String url = clientWrapper.uploadFile(file);
                            keepSupervisionUnitFiles.add(url + "#" + file.getOriginalFilename());
                        }
                        if (null != keepSupervisionUnitFiles && keepSupervisionUnitFiles.size() > 0) {
                            rectification.setSupervisionUnitSignature(new Gson().toJson(keepSupervisionUnitFiles));
                        }
                    }
                    if (null != rectificationFile && rectificationFile.length > 0) {
                        for (MultipartFile file : rectificationFile) {
                            String url = clientWrapper.uploadFile(file);
                            keepFileAtts.add(url + "#" + file.getOriginalFilename());
                            String pdfPath = docConverterUtils.converterUpdate(file);
                            if (StringUtils.isNotEmpty(pdfPath)) {
                                keepPreviewFileAtts.add(pdfPath);
                            } else {
                                keepPreviewFileAtts.add(url);
                            }
                        }
                        if (null != keepFileAtts && keepFileAtts.size() > 0) {
                            rectification.setRectificationFileAttachment(new Gson().toJson(keepFileAtts));
                        }
                        if (null != keepPreviewFileAtts && keepPreviewFileAtts.size() > 0) {
                            rectification.setRectificationFilePreviewAttachment(new Gson().toJson(keepPreviewFileAtts));
                        }
                    }
                    IndicationItems items = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "整改中");
                    rectification.setRectificationState(items == null ? null : items.getId());
                    items.setReferenceCount(items.getReferenceCount() + 1);
                    itemsList.add(items);
                    rectification.setDelayState(rectificationList.get(0).getDelayState());
                    rectification.setDelayReason(rectificationList.get(0).getDelayReason());
                    rectification.setDelayDate(rectificationList.get(0).getDelayDate());
                    dangerMapper.updateRectification(rectification);
                    //更新隐患的流程为已填写隐患整改信息
                    dangerDiscovery.setOperation(2);
                    dangerMapper.updateDanger(dangerDiscovery);
                    if (null != itemsList && itemsList.size() > 0)
                        factory.getMapper(IndicationItemsMapper.class).batchUpdate(itemsList);
                    factory.close();
                    msg.setDescription("隐患整改信息填写成功");
                    return msg;
                case 2:
                    //填写整改延期
                    rectification.setRectifier(rectificationList.get(0).getRectifier());
                    if (!user.getCode().equals(rectification.getRectifier().split("_")[0])) {
                        msg.setCode(BusinessCode.FAILURE.getCode());
                        msg.setDescription("隐患整改负责人是" + rectification.getRectifierName() + "，无法操作");
                        return msg;
                    }
                    rectification.setDelayState(1);
                    rectification.setRectificationResult("");
                    rectification.setCompleteTime(null);
                    rectification.setRectificationAttachment("");
                    dangerMapper.updateRectification(rectification);
                    //更新隐患处理流程为已填写隐患整改延期申请
                    dangerDiscovery.setOperation(3);
                    dangerMapper.updateDanger(dangerDiscovery);
                    msg.setDescription("整改延期申请成功");
                    if (null != itemsList && itemsList.size() > 0)
                        factory.getMapper(IndicationItemsMapper.class).batchUpdate(itemsList);
                    factory.close();
                    return msg;
                case 3:
                    //整改延期申请处理
                    if (rectification.getDelayState() == 2) {
                        //同意延期申请
                        rectification.setCompleteTime(rectificationList.get(0).getCompleteTime());
                        rectification.setDelayDate(rectificationList.get(0).getDelayDate());
                        dangerMapper.updateRectification(rectification);
                        dangerDiscovery.setOperation(1);
                        dangerMapper.updateDanger(dangerDiscovery);
                    } else {
                        //不同意延期申请
                        //处理延期申请成功后，将隐患流程修改成已确认整改信息状态，即可填写隐患整改信息
                        rectification.setCompleteTime(rectificationList.get(0).getCompleteTime());
                        rectification.setDeadline(rectificationList.get(0).getDeadline());
                        rectification.setSolution(rectificationList.get(0).getSolution());
                        rectification.setDelayDate(rectificationList.get(0).getDelayDate());
                        rectification.setDelayReason(rectification.getDelayReason());
                        factory.getMapper(HiddenDangerMapper.class).updateRectification(rectification);
                        dangerDiscovery.setOperation(1);
                        dangerMapper.updateDanger(dangerDiscovery);
                    }
                    msg.setDescription("整改延期申请处理成功");
                    factory.close();
                    return msg;
                case 4:
                    //填写验证结果
                    IndicationItems itemsRefused = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "整改驳回");
                    IndicationItems itemsUnfinish = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "未整改");
                    IndicationItems itemsFinished = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "已整改");
                    if (rectification.getReviewState() == 1) {
                        //验证通过
                        rectification.setReviewTime(date);
                        rectification.setCompleteTime(rectificationList.get(0).getCompleteTime());
                        rectification.setDelayDate(rectificationList.get(0).getDelayDate());
                        rectification.setRectificationState(itemsFinished == null ? null : itemsFinished.getId());
                        itemsFinished.setReferenceCount(itemsFinished.getReferenceCount() + 1);
                        itemsUnfinish.setReferenceCount(itemsRefused.getReferenceCount() - 1);
                        itemsList.add(itemsUnfinish);
                        itemsList.add(itemsFinished);
                        dangerMapper.updateRectification(rectification);
                        //修改隐患的流程为“已关闭状态，整个流程结束，闭环，已关闭”
                        dangerDiscovery.setOperation(5);
                        dangerMapper.updateDanger(dangerDiscovery);
                    } else {
                        //验证不通过
                        rectification.setRectificationState(itemsRefused != null ? itemsRefused.getId() : rectification.getRectificationState());
                        rectification.setReviewTime(date);
                        rectification.setCompleteTime(rectificationList.get(0).getCompleteTime());
                        rectification.setDelayDate(rectificationList.get(0).getDelayDate());
                        dangerMapper.updateRectification(rectification);
                        //验证不通过，将隐患状态修改成已确认整改信息状态，即可填写隐患整改信息
                        dangerDiscovery.setOperation(1);
                        dangerMapper.updateDanger(dangerDiscovery);
                    }
                    if (null != itemsList && itemsList.size() > 0)
                        factory.getMapper(IndicationItemsMapper.class).batchUpdate(itemsList);
                    msg.setDescription("整改结果记录验证处理成功");
                    factory.close();
                    return msg;
                default:
                    msg.setCode(BusinessCode.FREESNAP_ILEAGEL_OPERATIONTYPE.getCode());
                    msg.setDescription(BusinessCode.FREESNAP_ILEAGEL_OPERATIONTYPE.getDescription());
                    return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
            if (null != keepAtts && keepAtts.size() > 0) {
                for (String url : keepAtts) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<Boolean> isAllDealed(StaffBean user, Audit audit, Integer operation) {
        MessageBean<Boolean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Boolean.class);
        try (SessionFactory factory = new SessionFactory()) {
            //获取审批的隐患的主键id
            HiddenDangerMapper dangerMapper = factory.getMapper(HiddenDangerMapper.class);
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (null == idList || idList.size() <= 0) {
                msg.setCode(BusinessCode.DANGER_NOT_EXISIT.getCode());
                msg.setDescription("没有需要审批的隐患信息");
                factory.close();
                return msg;
            }
            List<HiddenDangerDiscovery> dangerDiscoveryList = dangerMapper.queryDangerByIdList(idList);
            if (null == dangerDiscoveryList || dangerDiscoveryList.size() <= 0) {
                msg.setCode(BusinessCode.DANGER_NOT_EXISIT.getCode());
                msg.setDescription("没有需要审批的隐患信息");
                factory.close();
                return msg;
            }
            switch (operation) {
                case 0:
                    //判断所有的要整改隐患整改人等信息是否已设置完毕
                    //根据隐患的operation不为0（草稿）或者1（已提交），则在该节点可以触发审批的通过操作即进入下一审批节点
                    for (HiddenDangerDiscovery dangerDiscovery : dangerDiscoveryList) {
                        if (dangerDiscovery.getOperation() != 1) {
                            msg.setCode(BusinessCode.FAILURE.getCode());
                            msg.setDescription("有存在没有指定整改人的隐患记录，请先确认隐患整改人等信息");
                            factory.close();
                            return msg;
                        }
                    }
                    msg.setData(true);
                    factory.close();
                    return msg;
                case 1:
                    //判断属于当前登录人负责整改的隐患是否已填写整改记录或者延期申请记录
                    //g根据隐患的state不为0（草稿）或者1（已提交）或者2（已确认/某个下面审批节点驳回回到此节点），则在该节点可以触发审批的通过操作即进入下一审批节点
                    for (HiddenDangerDiscovery dangerDiscovery : dangerDiscoveryList) {
                        if (dangerDiscovery.getOperation() != 2 && dangerDiscovery.getOperation() != 3) {
                            msg.setCode(BusinessCode.FAILURE.getCode());
                            msg.setDescription("有存在没有没有填写隐患整改记录或者已填写但是被驳回了整改信息，请先填写隐患整改记录或者申请延期");
                            factory.close();
                            return msg;
                        }
                    }
                    msg.setData(true);
                    factory.close();
                    return msg;
                case 2:
                    //验证判断
                    //只要有隐患未整改完成，就不能关闭该流程
                    for (HiddenDangerDiscovery dangerDiscovery : dangerDiscoveryList) {
                        if (dangerDiscovery.getState() != 5) {
                            msg.setCode(BusinessCode.FAILURE.getCode());
                            msg.setDescription("有存在未通过验证的隐患；无法结束流程");
                            factory.close();
                            return msg;
                        }
                    }
                    msg.setData(true);
                    factory.close();
                    return msg;
                default:
                    msg.setCode(BusinessCode.DANGER_EMPTY_OPERATIONTYPE.getCode());
                    msg.setDescription(BusinessCode.DANGER_EMPTY_OPERATIONTYPE.getDescription());
                    factory.close();
                    return msg;
            }
        } catch (Exception e) {
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> updateState(StaffBean user, String auditId, Boolean cancel) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Integer.class);
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            //根据审批记录id查询审批记录
            Audit audit = factory.getMapper(AuditMapper.class).queryOne(auditId);
            if (audit == null) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("审批记录不存在");
                return msg;
            }
            List<String> idList = new ArrayList<>();
            if (StringUtils.isNotEmpty(audit.getBusinessIds())) {
                idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            }
            if (null == cancel) {
                cancel = false;
            }
            if (cancel) {
                factory.getMapper(HiddenDangerMapper.class).updateDangerStateAndOperation(0, 0, idList);
            } else {
                List<HiddenDangerDiscovery> dangerDiscoveryList = factory.getMapper(HiddenDangerMapper.class).queryDangerByIdList(idList);
                Boolean flag = true;
                if (null != dangerDiscoveryList && dangerDiscoveryList.size() > 0) {
                    //查询审批的节点流转到哪里
                    MessageBean<?> history = flowService.history(audit.getSetCode(), audit.getTemplateKey(), audit.getId());
                    String nowNodeCode = "";
                    if (0 == history.getCode() && history.getData() != null) {
                        List<Map> historys = (List<Map>) history.getData();
                        if (historys != null && historys.size() > 0) {
                            List<Map> tasks = (List<Map>) historys.get(historys.size() - 1).get("tasks");
                            if (tasks != null && tasks.size() > 0 && tasks.get(0) != null) {
                                nowNodeCode = (String) tasks.get(0).get("taskCode");
                            }
                        }
                    }
                    for (HiddenDangerDiscovery dangerDiscovery : dangerDiscoveryList) {
                        List<HiddenDangerRectification> rectificationList = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(dangerDiscovery.getId());
                        HiddenDangerRectification rectification = rectificationList.get(0);
                        if (rectification.getDelayState() == 1) {
                            flag = false;
                            break;
                        }
                    }
                    for (HiddenDangerDiscovery dangerDiscovery : dangerDiscoveryList) {
                        if (null != dangerDiscovery.getOperation()) {
                            if (dangerDiscovery.getOperation() == 1) {
                                dangerDiscovery.setState(2);
                                List<HiddenDangerRectification> rectificationList = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(dangerDiscovery.getId());
                                HiddenDangerRectification rectification = rectificationList.get(0);
                                IndicationItems itemsRefused = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "整改驳回");
                                IndicationItems itemsUnfinish = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "未整改");
                                Date date = new Date();
                                if (rectification.getRectificationState().equals(itemsRefused.getId())) {
                                    //整改驳回
                                    if (StringUtils.isNotEmpty(nowNodeCode) && nowNodeCode.equals("Process-task1")) {
                                        dangerDiscovery.setState(1);
                                    } else if (StringUtils.isNotEmpty(nowNodeCode) && nowNodeCode.equals("Process-task2")) {
                                        dangerDiscovery.setState(2);
                                    }
                                    HiddenDangerRectification insertRectification = new HiddenDangerRectification();
                                    insertRectification.setId(DefaultIdGenerator.getInstance().generateLongId());
                                    insertRectification.setReviewer(rectification.getReviewer());
                                    insertRectification.setReviewerName(rectification.getReviewerName());
                                    insertRectification.setRectifier(rectification.getRectifier());
                                    insertRectification.setRectifierName(rectification.getRectifierName());
                                    insertRectification.setSolution(rectification.getSolution());
                                    insertRectification.setDeadline(rectification.getDeadline());
                                    insertRectification.setAddUser(rectification.getAddUser());
                                    insertRectification.setUpdateUser(rectification.getUpdateUser());
                                    insertRectification.setHiddenDangerId(rectification.getHiddenDangerId());
                                    insertRectification.setRectificationState(itemsUnfinish == null ? null : itemsUnfinish.getId());
                                    insertRectification.setAddTime(date);
                                    insertRectification.setUpdateTime(date);
                                    insertRectification.setDelayState(0);
                                    insertRectification.setConfirmPerson(rectification.getConfirmPerson());
                                    insertRectification.setConfirmPersonName(rectification.getConfirmPersonName());
                                    factory.getMapper(HiddenDangerMapper.class).insertRectification(insertRectification);
                                } else if (rectification.getDelayState() == 3) {
                                    //整改延期申请驳回
                                    HiddenDangerRectification rectificationInsert = new HiddenDangerRectification();
                                    BeanUtils.copyProperties(rectification, rectificationInsert);
                                    rectification.setRectificationResult("申请延期");
                                    rectification.setReviewResult(rectification.getRefuseDelayReason());
                                    factory.getMapper(HiddenDangerMapper.class).updateRectification(rectification);
                                    rectificationInsert.setId(DefaultIdGenerator.getInstance().generateLongId());
                                    rectificationInsert.setDeadline(rectification.getDeadline());
                                    rectificationInsert.setDelayReason(null);
                                    rectificationInsert.setDelayState(0);
                                    rectificationInsert.setRefuseDelayReason(null);
                                    rectificationInsert.setDelayDate(null);
                                    rectificationInsert.setAddTime(date);
                                    rectificationInsert.setAddUser(user.getName());
                                    rectificationInsert.setUpdateTime(date);
                                    rectificationInsert.setUpdateUser(user.getName());
                                    rectificationInsert.setConfirmPerson(rectification.getConfirmPerson());
                                    rectificationInsert.setConfirmPersonName(rectification.getConfirmPersonName());
                                    rectificationInsert.setRectificationResult(null);
                                    rectificationInsert.setReviewResult(null);
                                    factory.getMapper(HiddenDangerMapper.class).insertRectification(rectificationInsert);
                                } else if (rectification.getDelayState() == 2) {
                                    HiddenDangerRectification rectificationInsert = new HiddenDangerRectification();
                                    BeanUtils.copyProperties(rectification, rectificationInsert);
                                    rectification.setRectificationResult("申请延期");
                                    rectification.setReviewResult(rectification.getRefuseDelayReason());
                                    factory.getMapper(HiddenDangerMapper.class).updateRectification(rectification);
                                    rectificationInsert.setDeadline(rectification.getDelayDate());
                                    rectificationInsert.setId(DefaultIdGenerator.getInstance().generateLongId());
                                    rectificationInsert.setDelayReason(null);
                                    rectificationInsert.setDelayState(0);
                                    rectificationInsert.setRefuseDelayReason(null);
                                    rectificationInsert.setDelayDate(null);
                                    rectificationInsert.setRectificationResult(null);
                                    rectificationInsert.setReviewResult(null);
                                    rectificationInsert.setAddTime(date);
                                    rectificationInsert.setAddUser(user.getName());
                                    rectificationInsert.setUpdateTime(date);
                                    rectificationInsert.setUpdateUser(user.getName());
                                    factory.getMapper(HiddenDangerMapper.class).insertRectification(rectificationInsert);
                                }
                            } else if (dangerDiscovery.getOperation() == 2) {
                                List<HiddenDangerRectification> rectificationList = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(dangerDiscovery.getId());
                                String rectifier = rectificationList.get(0).getRectifier();
                                HiddenDangerRectification rectification = rectificationList.get(0);
                                IndicationItems itemsRefused = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "整改驳回");
                                IndicationItems itemsUnfinish = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "未整改");
                                IndicationItems itemsFinished = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "已整改");
                                Date date = new Date();
                                if (flag && hiddenDangerWorkFlow.equals(audit.getTemplateKey()) && rectifier.equals(dangerDiscovery.getDangerManager())) {
                                    rectification.setReviewState(1);
                                    factory.getMapper(HiddenDangerMapper.class).updateRectification(rectification);
                                    dangerDiscovery.setState(6);
                                    dangerDiscovery.setOperation(5);
                                    nowNodeCode = "Process-task4";
                                } else {
                                    if (user.getCode().equals(rectifier.split("_")[0])) {
                                        dangerDiscovery.setState(3);
                                    }
                                }
                            } else if (dangerDiscovery.getOperation() == 3) {
                                List<HiddenDangerRectification> rectificationList = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(dangerDiscovery.getId());
                                String rectifier = rectificationList.get(0).getRectifier();
                                if (user.getCode().equals(rectifier.split("_")[0])) {
                                    dangerDiscovery.setState(4);
                                }
                            } else if (dangerDiscovery.getOperation() == 4) {
                                dangerDiscovery.setOperation(1);
                                dangerDiscovery.setState(2);
                            } else if (dangerDiscovery.getOperation() == 5 && "Process-task3".equals(audit.getNowNodeCode())) {
                                if (StringUtils.isNotEmpty(nowNodeCode) && !"Process-task3".equals(nowNodeCode)) {
                                    if (("Process-task0").equals(nowNodeCode)) {
                                        dangerDiscovery.setState(1);
                                    } else if (("Process-task1").equals(nowNodeCode)) {
                                        dangerDiscovery.setState(1);
                                    } else if (("Process-task2").equals(nowNodeCode)) {
                                        dangerDiscovery.setState(2);
                                        dangerDiscovery.setOperation(2);
                                    } else if (("Process-task4").equals(nowNodeCode)) {
                                        dangerDiscovery.setState(6);
                                    }
                                } else {
                                    dangerDiscovery.setState(6);
                                }
                            } else if (dangerDiscovery.getOperation() == 5 && "Process-task4".equals(audit.getNowNodeCode())) {
                                if (StringUtils.isNotEmpty(nowNodeCode) && !"Process-task4".equals(nowNodeCode)) {
                                    if (("Process-task0").equals(nowNodeCode)) {
                                        dangerDiscovery.setState(1);
                                    } else if (("Process-task1").equals(nowNodeCode)) {
                                        dangerDiscovery.setState(1);
                                    } else if (("Process-task2").equals(nowNodeCode)) {
                                        dangerDiscovery.setState(2);
                                    } else if (("Process-task3").equals(nowNodeCode)) {
                                        dangerDiscovery.setState(3);
                                    }
                                } else {
                                    dangerDiscovery.setState(5);
                                }
                            }
                        }
                    }
                    //修改审批单的审批节点
                    if (StringUtils.isEmpty(nowNodeCode) && audit.getNowNodeCode().equals("Process-task4")) {
                        //流程结束
                        nowNodeCode = "Process-end0";
                        audit.setState(2);
                    }
                    audit.setNowNodeCode(nowNodeCode);
                    factory.getMapper(AuditMapper.class).update(audit);
                    //批量修改隐患的状态
                    factory.getMapper(HiddenDangerMapper.class).batchUpdateDanger(dangerDiscoveryList);
                }
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<HiddenDangerDiscovery> queryDangerOne(String id) {
        MessageBean<HiddenDangerDiscovery> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.DANGER_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.DANGER_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            HiddenDangerDiscovery dangerDiscovery = factory.getMapper(HiddenDangerMapper.class).queryDangerOne(id);
            getNames(dangerDiscovery);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取隐患详情成功");
            msg.setData(dangerDiscovery);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> batchDelete(List<String> idList) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (null == idList || idList.size() <= 0) {
                msg.setCode(BusinessCode.DANGER_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.DANGER_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            List<String> delIdList = new ArrayList<>();
            List<String> delAtts = new ArrayList<>();
            for (String id : idList) {
                HiddenDangerDiscovery dangerDiscovery = queryDangerOne(id).getData();
                if (null != dangerDiscovery && (dangerDiscovery.getState() == 0) || dangerDiscovery.getState() == 7) {
                    delIdList.add(id);
                    if (StringUtils.isEmpty(dangerDiscovery.getFreeSnapId()) && StringUtils.isNotEmpty(dangerDiscovery.getAttachment())) {
                        for (String att : dangerDiscovery.getAttachment().split("[,，]")) {
                            delAtts.add(att);
                        }
                    }
                }
            }
            if (null == delIdList || delIdList.size() <= 0) {
                msg.setCode(BusinessCode.DANGER_NOT_DRAFT.getCode());
                msg.setDescription(BusinessCode.DANGER_NOT_DRAFT.getDescription());
                return msg;
            }
            Integer value = factory.getMapper(HiddenDangerMapper.class).batchDeleteDanger(delIdList);
            if (value > 0) {
                if (null != delAtts && delAtts.size() > 0) {
                    for (String att : delAtts) {
                        clientWrapper.deleteFile(att.split("#")[0]);
                    }
                }
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription(BusinessCode.SUCCESS.getDescription());
                msg.setData(value);
                factory.close();
                return msg;
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription(BusinessCode.FAILURE.getDescription());
                msg.setData(value);
                factory.close(false);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<HiddenDangerDiscovery>> queryDangerByCondition(StaffBean user, String description,
                                                                               String dangerType, String dangerLevel, String corpCode, String gridCode, String checkUnit, Integer state, Date startTime, Date endTime, Integer start,
                                                                               Integer rows, Integer mobile, Integer queryAll, String querySubmitterCode, String keyword) {
        MessageBean<DataBean<HiddenDangerDiscovery>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            String codes;
            if (null != queryAll && queryAll == 1) {
                // 用于首页工作台跳转
                codes = "('" + corpCode + "')";
                //设置开始、结束时间
                if (null == startTime) {
                    Calendar calendar = Calendar.getInstance();
                    int year = calendar.get(Calendar.YEAR);
                    int month = calendar.get(Calendar.MONTH);
                    calendar.set(year, 0, 1, 0, 0, 0);
                    startTime = calendar.getTime();
                }
                if (null == endTime) {
                    Calendar calendar = Calendar.getInstance();
                    int year = calendar.get(Calendar.YEAR);
                    int month = calendar.get(Calendar.MONTH);
                    calendar.set(year, month + 1, 1, 0, 0, 0);
                    endTime = calendar.getTime();
                }
                if (null == state) {
                    state = 3;
                }
            } else {
                codes = util.getCodes(corpCode);
            }
//            if(null != querySubmitterCode && !querySubmitterCode.isEmpty()){
//                List data = getPort().staff(querySubmitterCode).getData();
//                if(null == data || data.isEmpty()){
//                    msg.setCode(BusinessCode.SUBMITTER_NOT_FOUND.getCode());
//                    msg.setDescription(BusinessCode.SUBMITTER_NOT_FOUND.getDescription());
//                    return msg;
//                }
//                StaffBean submitter = (StaffBean)data.get(0);
//                querySubmitterCode = querySubmitterCode + "_" + submitter.getUserid();
//            }
            List<HiddenDangerDiscovery> list = new ArrayList<>();
            List<HiddenDangerDiscovery> list1 = null;
            Integer totalNumber = 0;
            HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
            if (null != mobile && mobile == 1) {
                list1 = mapper.queryMobileDangerByCondition(description, dangerType, dangerLevel, codes, gridCode, corpCode, checkUnit, state, startTime, endTime, null, null, querySubmitterCode, keyword);
                totalNumber = mapper.countMobileDangerByCondition(description, dangerType, dangerLevel, codes, gridCode, corpCode, checkUnit, state, startTime, endTime, querySubmitterCode, keyword);
            } else {
                list1 = mapper.queryDangerByCondition1(description, dangerType, dangerLevel, codes, gridCode, checkUnit, corpCode, state, startTime, endTime, querySubmitterCode, null);
                if (null != state && state == 3) {
                    // 获取所有超期整改数据，包括超期未整改和超期已整改数据
                    list1.forEach(item -> getIsDelay(item));
                    list1 = list1.stream().filter(bean -> null != bean.getIsDelay() && bean.getIsDelay() == 2).collect(Collectors.toList());
                }
                totalNumber = list1.size();
            }
            // 判断是否是集团层次的查询,如果是，则查询所有提交人是当前登陆人的草稿数据,移动端不做查询
            Integer num = 0;
            if (null == mobile || mobile != 1) {
                if ("('776B361BFFAC4F00BBF459CD1303A8B2')".equals(codes) && (null == state || state == 0)) {
                    String submitterCode = user.getCode() + "_" + user.getUserid();
                    List<HiddenDangerDiscovery> list2 = mapper.queryDraftDangerByCondition(description, dangerType, dangerLevel, submitterCode, gridCode, checkUnit, startTime, endTime);
                    if (null != list2 && list2.size() > 0) {
                        Set<String> collect = list1.stream().map(HiddenDangerDiscovery::getId).collect(Collectors.toSet());
                        // 过滤掉重复数据
                        List<HiddenDangerDiscovery> collect1 = list2.stream().filter(bean -> !collect.contains(bean.getId())).map(bean -> {
                            bean.setEditState(1);
                            return bean;
                        }).collect(Collectors.toList());
                        num = collect1.size();
                        list.addAll(collect1);
                    }
                }
            }
            int count = 0;
            // 检测当前登陆人是否有系统管理员权限
            Boolean flag = getAuthority(user.getCode());
            // 草稿数据只有提交人自己能够查看
            if (null != list1 && list1.size() > 0) {
                for (HiddenDangerDiscovery dangerDiscovery : list1) {
                    if (dangerDiscovery.getState() == 0) {
                        if (dangerDiscovery.getSubmitterCode().equals(user.getCode() + "_" + user.getUserid())) {
                            dangerDiscovery.setEditState(1);
                            list.add(dangerDiscovery);
                        } else {
                            count++;
                        }
                    } else {
                        // 系统管理员可以修改
                        if (flag) {
                            dangerDiscovery.setEditState(1);
                        } else {
                            // 创建者可以修改
                            if (dangerDiscovery.getSubmitterCode().equals(user.getCode() + "_" + user.getUserid())) {
                                dangerDiscovery.setEditState(1);
                            }
                        }
                        if (null != dangerDiscovery.getFlowState() && dangerDiscovery.getFlowState() == 2 && dangerDiscovery.getSubmitterCode().equals(user.getCode() + "_" + user.getUserid())) {
                            dangerDiscovery.setWithdrawState(1);
                        }
                        list.add(dangerDiscovery);
                    }
                }
            }
            totalNumber = totalNumber - count + num;
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = totalNumber > rows
                    ? totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1 : 1;
            DataBean<HiddenDangerDiscovery> dataBean = new DataBean<>();
            dataBean.setPageSize(rows);
            start = start == null ? 0 : start;
            Integer end = start == 0 ? rows : start + rows;
            if (end > list.size()) {
                end = list.size();
                if (start > end) {
                    start = end;
                }
            }
            list = list.subList(start, end);
            list.forEach(item -> getNames(item));
            dataBean.setList(list);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setData(dataBean);
            msg.setDescription("获取隐患列表成功");
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<HiddenDangerDiscovery>> queryDangerByCheckRecordId(String checkRecordId, Integer
            start,
                                                                                   Integer rows) {
        MessageBean<DataBean<HiddenDangerDiscovery>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<HiddenDangerDiscovery> list = factory.getMapper(HiddenDangerMapper.class)
                    .queryDangerByCheckRecordId(checkRecordId, start, rows);
            Integer totalNumber = factory.getMapper(HiddenDangerMapper.class).countDangerByCheckRecordId(checkRecordId);
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = totalNumber > rows
                    ? totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1 : 1;
            list.forEach(item -> getNames(item));
            DataBean<HiddenDangerDiscovery> dataBean = new DataBean<>();
            dataBean.setPageSize(rows);
            dataBean.setList(list);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setData(dataBean);
            msg.setDescription("获取隐患列表成功");
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<HiddenDangerDiscovery>> queryTempDanger(Integer start, Integer rows) {
        MessageBean<DataBean<HiddenDangerDiscovery>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            // 获取已整改的状态的id
            IndicationItems items = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态",
                    "已整改");
            if (null == items) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription(BusinessCode.EXCEPTION.getDescription());
                return msg;
            }
            List<HiddenDangerDiscovery> list = factory.getMapper(HiddenDangerMapper.class)
                    .queryTempDanger(items.getId(), start, rows);
            Integer totalNumber = factory.getMapper(HiddenDangerMapper.class).countTempDanger(items.getId());
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = totalNumber > rows
                    ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<HiddenDangerDiscovery> dataBean = new DataBean<>();
            if (list != null && !list.isEmpty()) {
                list.forEach(item -> setNames(item));
            }
            dataBean.setList(list);
            dataBean.setPageSize(rows);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取临时隐患列表成功");
            msg.setData(dataBean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<List<HiddenDangerRectification>> queryRectificationByDangerRecordId(String dangerId) {
        MessageBean<List<HiddenDangerRectification>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(dangerId)) {
                msg.setCode(BusinessCode.DANGER_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.DANGER_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            HiddenDangerDiscovery dangerDiscovery = queryDangerOne(dangerId).getData();
            if (null == dangerDiscovery) {
                msg.setCode(BusinessCode.DANGER_NOT_EXISIT.getCode());
                msg.setDescription(BusinessCode.DANGER_NOT_EXISIT.getDescription());
                return msg;
            }
            List<HiddenDangerRectification> list = factory.getMapper(HiddenDangerMapper.class)
                    .queryRectificationByDangerRecordId(dangerId);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取隐患的整改列表成功");
            list.forEach(item -> getRectification(item));
            msg.setData(list);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<HiddenDangerRectification> queryOneRectificationById(String rectificationId) {
        MessageBean<HiddenDangerRectification> msg = new MessageEntity<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(rectificationId)) {
                msg.setCode(BusinessCode.DANGERRECTIFICATION_NOT_EXISIT.getCode());
                msg.setDescription(BusinessCode.DANGERRECTIFICATION_NOT_EXISIT.getDescription());
                return msg;
            }
            HiddenDangerRectification rectification = factory.getMapper(HiddenDangerMapper.class)
                    .queryOneRectificationById(rectificationId);
            msg.setData(rectification);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public String generateCode(SessionFactory factory, HiddenDangerDiscovery dangerDiscovery) {
        String date = format.format(new Date());
        Integer counter = factory.getMapper(HiddenDangerMapper.class).countCode(date.substring(2, 4));
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        nf.setMaximumIntegerDigits(4); // 设置最大整数位数
        nf.setMinimumIntegerDigits(4); // 设置最小整数位数
        StringBuilder sb = new StringBuilder();
        sb.append("YD").append(date.substring(2, 4)).append(nf.format(counter));
        return sb.toString();
    }

    @Override
    public void getNames(HiddenDangerDiscovery bean) {
        if (null != bean) {
            setNames(bean);
            Port port = getPort();
            if (StringUtils.isNotEmpty(bean.getInnerStaff())) {
                List<String> origin = JSONObject.parseArray(bean.getInnerStaff(), String.class);
                List<String> names = new ArrayList<>();
                for (String innerStaff : origin) {
                    String staffCode = innerStaff.split("_")[0];
                    List<DeptBean> departmentTreeBeanList = port.dept(staffCode).getData();
                    List<StaffBean> staffBeanList = port.staff(staffCode, null).getData();
                    if (null != departmentTreeBeanList && departmentTreeBeanList.size() > 0 && null != staffBeanList && staffBeanList.size() > 0) {
                        names.add(staffBeanList.get(0).getName() + "_" + departmentTreeBeanList.get(0).getName());
                    }
                }
                bean.setInnerStaffName(new Gson().toJson(names));
            }
        }
    }

    @Override
    public MessageBean<Boolean> isSafetyRole(StaffBean user) {
        MessageBean<Boolean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Boolean.class);
        try (SessionFactory factory = new SessionFactory()) {
            Map<String, Object> map = (Map<String, Object>) util.getRolesAndGroupsByStaff(user.getCode(), 1024).getData();
            if (null != map && !map.isEmpty()) {
                List<RoleBean> roleBeanList = (List<RoleBean>) map.get("role");

                List<String> roleCodeList = new ArrayList<>();
                if (null != roleBeanList && roleBeanList.size() > 0) {
                    roleCodeList = roleBeanList.stream().map(RoleBean::getCode).collect(Collectors.toList());
                    if (roleCodeList.size() > 1) {
                        msg.setData(true);
                        return msg;
                    }
                }
            }
            msg.setData(false);
            factory.close();
            return msg;
        }
    }

    private void getIsDelay(HiddenDangerDiscovery danger) {
        if (danger != null) {
            SessionFactory factory = new SessionFactory();
            List<HiddenDangerRectification> rectificationList = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(danger.getId());
            if (null != rectificationList && rectificationList.size() > 0) {
                HiddenDangerRectification rectification = rectificationList.get(0);
                // 整改情况判断
                OverdueJudgmentUtil.setIsDelay3(danger, rectification);
            }
            factory.close();
        }
    }

    private void setNames(HiddenDangerDiscovery danger) {
        if (danger != null) {
            Map<String, DictData> cacheMap = dataService.getCacheMap();
            Map<String, IndicationItems> cache = indicationItemsService.getCacheMap();
            if (StringUtils.isNotBlank(danger.getElementFristType())) {
                DictData element = cacheMap.get(danger.getElementFristType());
                danger.setElementFristTypeName(element != null ? element.getDictLabel() : "");
            }
            if (StringUtils.isNotBlank(danger.getElementSecondType())) {
                DictData element = cacheMap.get(danger.getElementSecondType());
                danger.setElementSecondTypeName(element != null ? element.getDictLabel() : "");
            }
            if (StringUtils.isNotBlank(danger.getDangerType())) {
                IndicationItems indication = cache.get(danger.getDangerType());
                danger.setDangerTypeName(indication != null ? indication.getName() : "");
            }
            if (StringUtils.isNotBlank(danger.getDangerLevel())) {
                IndicationItems indication = cache.get(danger.getDangerLevel());
                danger.setDangerLevelName(indication != null ? indication.getName() : "");
            }
            SessionFactory factory = new SessionFactory();
            if (StringUtils.isNotEmpty(danger.getCorpCode())) {
                CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(danger.getCorpCode());
                danger.setCorpName(corpBean == null ? null : corpBean.getCorpName());
            }
            List<HiddenDangerRectification> rectificationList = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(danger.getId());
            if (null != rectificationList && rectificationList.size() > 0) {
                HiddenDangerRectification rectification = rectificationList.get(0);
                danger.setRectificationId(rectificationList.get(0).getId());
                danger.setRectifier(rectificationList.get(0).getRectifier());
                danger.setDeadline(rectificationList.get(0).getDeadline());
                danger.setRectifierName(rectificationList.get(0).getRectifierName());
                danger.setRectificationResult(rectificationList.get(0).getRectificationResult());
                danger.setReviewerName(rectificationList.get(0).getReviewerName());
                danger.setReviewer(rectificationList.get(0).getReviewer());
                danger.setSolution(rectificationList.get(0).getSolution());
                danger.setReviewTime(rectificationList.get(0).getReviewTime());
                danger.setReviewResult(rectificationList.get(0).getReviewResult());
                danger.setConfirmPerson(rectificationList.get(0).getConfirmPerson());
                danger.setConfirmPersonName(rectificationList.get(0).getConfirmPersonName());
                danger.setRectificationAttachment(rectificationList.get(0).getRectificationAttachment());
                if (StringUtils.isNotEmpty(rectificationList.get(0).getRectificationState())) {
                    IndicationItems indication = cache.get(rectificationList.get(0).getRectificationState());
                    danger.setDangerRectificationStateName(indication != null ? indication.getName() : "");
                }
                // 整改情况判断
                OverdueJudgmentUtil.setIsDelay3(danger, rectification);
            }
            factory.close();
        }
    }

    public void getRectification(HiddenDangerRectification bean) {
        if (null != bean) {
            Port port = getPort();
            if (StringUtils.isNotEmpty(bean.getReviewer())) {
                List<StaffBean> staffBeanList = port.staff(bean.getReviewer(), null).getData();
                if (null != staffBeanList && staffBeanList.size() > 0) {
                    bean.setReviewerName(staffBeanList.get(0).getName());
                }
            }

            if (StringUtils.isNotEmpty(bean.getRectifier())) {
                List<StaffBean> staffBeanList = port.staff(bean.getRectifier(), null).getData();
                if (null != staffBeanList && staffBeanList.size() > 0) {
                    bean.setRectifierName(staffBeanList.get(0).getName());
                }
            }
        }
    }

    public Port getPort() {
        SecretBean secretBean = new SecretBean();
        secretBean.setAppid(appid);
        secretBean.setSecret(secret);
        return new Port(secretBean);
    }

    @Override
    public void editApproval(Audit audit) {
        try (SessionFactory factory = new SessionFactory()) {
            //隐患整改流程通过，生成隐患整改报告
            // 获取业务id
            String businessIds = audit.getBusinessIds();
            List<String> idLists = JSONArray.parseArray(businessIds, String.class);
            audit.getBusinessIds();
            audit.setState(2);
            factory.getMapper(AuditMapper.class).update(audit);
            // 生成隐患报告
            HiddenDangerRectificationServiceImpl.generateHiddenDangerRectificationReport(factory, idLists);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    @Override
    public void discardApproval(Audit audit) {

    }

    @Override
    public void processDiscard(Audit audit) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            // 获取业务id
            String businessIds = audit.getBusinessIds();
            List<String> idLists = JSONArray.parseArray(businessIds, String.class);
            if (null != idLists) {
                // 将隐患信息回滚草稿
                factory.getMapper(HiddenDangerMapper.class).updateDangerStateAndOperation(0, 0, idLists);
                // 隐患废弃后，删掉对应的隐患整改通知书信息
                HiddenDangerRectificationServiceImpl.DeleteNotice(factory, idLists);
            }
            factory.close();
        } catch (Exception e) {
            if (null != factory) {
                factory.close(false);
            }
            logger.error(e.getMessage(),e);
        }
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(HiddenDangerDiscoveryServiceImpl.class.getName(), this);
        scheduler.start();
        try (SessionFactory factory = new SessionFactory()) {
            //超期未整改企业微信消息通知
            List<HiddenDangerDiscovery> list = factory.getMapper(HiddenDangerMapper.class).queryDangerByCondition(null,
                    null, null, null, null, null, null, null, null, null, null, null);
            IndicationItems data = indicationItemsService.matchItems("隐患整改状态", "已整改");
            if (null != list && list.size() > 0) {
                for (HiddenDangerDiscovery dangerDiscovery : list) {

                }
            }
        }
    }


    /**
     * 查询人员是否拥有系统管理员权限
     *
     * @param userCode 用户code
     * @return
     */
    private Boolean getAuthority(String userCode) {
        try {
            // 获取人员拥有的角色列表
            MessageBean<?> msg = util.getRolesAndGroupsByStaff(userCode, 1024);
            if (msg.getCode() == 0 && msg.getData() != null) {
                Map map = (Map) msg.getData();
                if (!map.isEmpty()) {
                    // 获取角色权限列表
                    List<RoleBean> roleList = (List<RoleBean>) map.get("role");
                    if (null != roleList && roleList.size() > 0) {
                        List<String> roles = roleList.stream().map(RoleBean::getCode).collect(Collectors.toList());
                        if (roles.contains(systemAdministratorCode)) {
                            return true;
                        }
                    }
                }
            }
            return false;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return false;
        }
    }

    /**
     * 获取部门下人员信息，包括子部门
     *
     * @param port
     * @param deptBean
     * @return
     */
    private List<StaffBean> getDeptStaff(Port port, DeptBean deptBean) {
        MessageBean<List> msg = port.depstaff(orgCode, deptBean.getCode(), 1);
        if (msg.getCode() == 0 && msg.getData() != null) {
            List<StaffBean> list = msg.getData();
            if (null != list && list.size() > 0) {
                return list;
            }
        }
        return null;
    }

    private MessageBean<Integer> checkDanger(HiddenDangerDiscovery dangerDiscovery) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(),
                BusinessCode.SUCCESS.getDescription(), Integer.class);
        if (StringUtils.isEmpty(dangerDiscovery.getCorpCode())) {
            msg.setCode(BusinessCode.DANGER_EMPTY_CORPCODE.getCode());
            msg.setDescription(BusinessCode.DANGER_EMPTY_CORPCODE.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(dangerDiscovery.getGridCode())) {
            msg.setCode(BusinessCode.DANGER_EMPTY_GRIDCODE.getCode());
            msg.setDescription(BusinessCode.DANGER_EMPTY_GRIDCODE.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(dangerDiscovery.getDescription())) {
            msg.setCode(BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
            msg.setDescription(BusinessCode.DANGER_EMPTY_DESCRIPTION.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(dangerDiscovery.getElementFristType())) {
            msg.setCode(BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
            msg.setDescription("一级分类不能为空");
            return msg;
        }
        if (StringUtils.isEmpty(dangerDiscovery.getElementSecondType())) {
            msg.setCode(BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
            msg.setDescription("二级分类不能为空");
            return msg;
        }
        if (StringUtils.isEmpty(dangerDiscovery.getDangerType())) {
            msg.setCode(BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
            msg.setDescription("排序不能为空");
            return msg;
        }
        if (StringUtils.isEmpty(dangerDiscovery.getDangerLevel())) {
            msg.setCode(BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
            msg.setDescription("隐患分级不能为空");
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<List<HiddenDangerDiscovery>> queryDangerByIdList(List<String> idList) {
        MessageBean<List<HiddenDangerDiscovery>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            if (idList == null || idList.size() <= 0) {
                msg.setData(null);
                return msg;
            }
            List<HiddenDangerDiscovery> dangerDiscoveryList = factory.getMapper(HiddenDangerMapper.class).queryDangerByIdList(idList);
            dangerDiscoveryList.forEach(item -> getNames(item));
            msg.setData(dangerDiscoveryList);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<String> importImage(StaffBean user, String corpCode, MultipartFile[] files) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), String.class);
        //保存上传的文件地址，要是上传出错，将已上传的数据删除
        List<String> newAtts = new ArrayList<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (files == null) {
                msg.setCode(BusinessCode.PARAM_NOT_EMPTY.getCode());
                msg.setDescription("未上传隐患照片");
                return msg;
            }
            if (files.length > 10) {
                msg.setCode(BusinessCode.PARAM_NOT_EMPTY.getCode());
                msg.setDescription("最多上传10张隐患照片");
                return msg;
            }
            List<HiddenDangerDiscovery> dangerDiscoveryList = new ArrayList<>();
            Date date = new Date();
            //一张照片生成一条隐患记录
            for (MultipartFile file : files) {
                HiddenDangerDiscovery dangerDiscovery = new HiddenDangerDiscovery();
                dangerDiscovery.setId(DefaultIdGenerator.getInstance().generateLongId());
                dangerDiscovery.setAddTime(date);
                dangerDiscovery.setAddUser(user.getCode());
                dangerDiscovery.setAddUserName(user.getName());
                dangerDiscovery.setUpdateTime(date);
                dangerDiscovery.setUpdateUser(user.getCode());
                dangerDiscovery.setUpdateUserName(user.getName());
                dangerDiscovery.setSubmitterCode(user.getCode() + "_" + user.getUserid());
                dangerDiscovery.setSubmitterDepartment(user.getDepartmentCode());
                dangerDiscovery.setDerivation(1);
                dangerDiscovery.setCorpCode(corpCode);
                dangerDiscovery.setCode(generateCode(factory, dangerDiscovery));
                dangerDiscovery.setState(0);
                String url = clientWrapper.uploadFile(file);
                List<String> urlList = new ArrayList<>();
                urlList.add(url + "#" + file.getOriginalFilename());
                dangerDiscovery.setAttachment(new Gson().toJson(urlList));
                newAtts.add(url);
                dangerDiscoveryList.add(dangerDiscovery);
            }
            if (dangerDiscoveryList != null && dangerDiscoveryList.size() > 0) {
                factory.getMapper(HiddenDangerMapper.class).batchInsertDanger(dangerDiscoveryList);
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            if (null != newAtts && newAtts.size() > 0) {
                for (String url : newAtts) {
                    clientWrapper.deleteFile(url);
                }
            }
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<List<HiddenDangerDiscovery>> getAll(StaffBean user, String description, String
            dangerType, String dangerLevel, String corpCode, String gridCode, String checkUnit, Integer state, Date
                                                                   startTime, Date endTime) {
        MessageBean<List<HiddenDangerDiscovery>> messageBean = new MessageBean<>();
        MessageBean<DataBean<HiddenDangerDiscovery>> msg = queryDangerByCondition(user, description, dangerType, dangerLevel, corpCode, gridCode, checkUnit, state, startTime, endTime, null, null, null, null, null, null);
        analyseHiddenDangerDiscovery(messageBean, msg);
        return messageBean;
    }

    @Override
    public MessageBean<Integer> update(StaffBean user, String id, String elementFristType, String
            elementSecondType, String dangerType, String dangerLevel) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Integer.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("id不能为空");
                return msg;
            }
            HiddenDangerDiscovery dangerDiscovery = factory.getMapper(HiddenDangerMapper.class).queryDangerOne(id);
            if (null == dangerDiscovery) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("隐患不存在");
                return msg;
            }
            dangerDiscovery.setElementFristType(elementFristType);
            dangerDiscovery.setElementSecondType(elementSecondType);
            dangerDiscovery.setDangerType(dangerType);
            dangerDiscovery.setDangerLevel(dangerLevel);
            Integer integer = factory.getMapper(HiddenDangerMapper.class).updateDanger(dangerDiscovery);
            msg.setData(integer);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> updateCheckUnit() {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "更新检查单位成功", Integer.TYPE);
        try (SessionFactory factory = new SessionFactory()) {
            List<HiddenDangerDiscovery> checkUnitEmpty = factory.getMapper(HiddenDangerMapper.class).getCheckUnitEmpty();
            if (null != checkUnitEmpty && checkUnitEmpty.size() > 0) {
                for (HiddenDangerDiscovery discovery : checkUnitEmpty) {
                    if (StringUtils.isNotEmpty(discovery.getSubmitterCode())) {
                        String userCode = discovery.getSubmitterCode().split("_")[0];
                        if (StringUtils.isNotEmpty(userCode)) {
                            MessageBean<?> corpMsg = util.corp(userCode);
                            if (corpMsg.getCode() == 0 && null != corpMsg.getData()) {
                                DepartmentTreeBean corp = (DepartmentTreeBean) corpMsg.getData();
                                discovery.setCheckUnit(corp.getDepartmentCode());
                                discovery.setCheckUnitName(corp.getName());
                            }
                        }
                    }
                }
                Integer value = factory.getMapper(HiddenDangerMapper.class).batchUpdateCheckUnit(checkUnitEmpty);
                msg.setData(value);
            }
            return msg;
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return MessageBean.create(BusinessCode.EXCEPTION.getCode(),BusinessCode.EXCEPTION.getDescription(),Integer.class);
        }
    }

    @Override
    public XSSFWorkbook export(StaffBean user, String description, String dangerType, String dangerLevel, String
            corpCode, String gridCode, String checkUnit, Integer state, Date startTime, Date endTime, InputStream
                                       inputStream, String exportIds) {
        // 获取台账信息
        List<HiddenDangerDiscovery> discoveryList = null;
        List<String> ids = null;
        MessageBean<List<HiddenDangerDiscovery>> msg = new MessageBean<>();
        if (null != exportIds) {
            ids = Arrays.stream(exportIds.split(",")).collect(Collectors.toList());
            try (SessionFactory factory = new SessionFactory()) {
                List<HiddenDangerDiscovery> hiddenDangerDiscoveries = factory.getMapper(HiddenDangerMapper.class).queryDangerByCondition1(null, null, null, null, null, null, null, null, null, null, null, ids);
                for (HiddenDangerDiscovery dangerDiscovery : hiddenDangerDiscoveries) {
                    setNames(dangerDiscovery);
                }
                MessageBean<DataBean<HiddenDangerDiscovery>> messageBean = new MessageBean<>();
                DataBean<HiddenDangerDiscovery> dataBean = new DataBean<>();
                dataBean.setList(hiddenDangerDiscoveries);
                messageBean.setCode(BusinessCode.SUCCESS.getCode());
                messageBean.setData(dataBean);
                messageBean.setDescription("获取隐患列表成功");
                analyseHiddenDangerDiscovery(msg, messageBean);
            } catch (Exception e) {
                msg.setCode(BusinessCode.FAILURE.getCode());
            }
        } else {
            msg = getAll(user, description, dangerType, dangerLevel, corpCode, gridCode, checkUnit, state, startTime, endTime);
        }
        if (msg.getCode() == BusinessCode.SUCCESS.getCode() && msg.getData() != null) {
            discoveryList = msg.getData();
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(inputStream);
            // 导出检查记录数据
            if (null != discoveryList && discoveryList.size() > 0) {
                int index = 1;
                int rowNum = 2;
                CellStyle cellStyle = workbook.createCellStyle();
                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                cellStyle.setWrapText(true);
                XSSFSheet sheet = workbook.getSheetAt(0);
                XSSFDrawing drawing = sheet.createDrawingPatriarch();
                // 设置检查记录内容
                XSSFRow row;
                for (HiddenDangerDiscovery discovery : discoveryList) {
                    row = sheet.createRow(rowNum);
                    row.createCell(0).setCellValue(index);
                    row.createCell(1).setCellValue(discovery.getDangerTypeName());
                    row.createCell(2).setCellValue(discovery.getLocation());
                    row.createCell(3).setCellValue(discovery.getDescription());
                    row.createCell(4).setCellValue(discovery.getDangerLevelName());
                    row.createCell(5).setCellValue(discovery.getLegalBasis());
                    row.createCell(6).setCellValue(discovery.getDiscoveryTimeStr());
                    row.createCell(7).setCellValue(discovery.getNoticeCode());
                    row.createCell(8).setCellValue(discovery.getGridName());
                    row.createCell(9).setCellValue("是");
                    row.createCell(10).setCellValue("是");
                    row.createCell(11).setCellValue(discovery.getDeadlineStr());
                    row.createCell(12).setCellValue(discovery.getSolution());
                    row.createCell(13).setCellValue(discovery.getDiscovererDepartment());
                    row.createCell(14).setCellValue(discovery.getRectifierName());
                    row.createCell(15).setCellValue(discovery.getRectifierTel());
                    row.createCell(16).setCellValue(discovery.getRectifierUnit());
                    row.createCell(17).setCellValue(discovery.getElementFristTypeName());
                    row.createCell(18).setCellValue(discovery.getElementSecondTypeName());
                    if (discovery.getFlowState()==1){
                        row.createCell(19).setCellValue("草稿");
                    }else if (discovery.getFlowState()==2){
                        row.createCell(19).setCellValue("待整改");
                    }else if (discovery.getFlowState()==3){
                        row.createCell(19).setCellValue("待验证");
                    }else if (discovery.getFlowState()==4){
                        row.createCell(19).setCellValue("待验收");
                    }else if (discovery.getFlowState()==5){
                        row.createCell(19).setCellValue("关闭");
                    }
                    row.createCell(20).setCellValue(discovery.getRemark());
//                    String attachment = discovery.getAttachment();
//                    if (StringUtils.isNotEmpty(attachment)) {
//                        List<String> list = JSONArray.parseArray(attachment, String.class);
//                        String url = null;
//                        if (null != list && list.size() > 0) {
//                            // 如果有多张图片，则取第一张
//                            url = list.get(0).split("#")[0];
//                        }
//                        if (null != url) {
//                            // 对图片单独捕获异常
//                            try {
//                                URL imgUrl = new URL(url);
//                                String suffix = url.substring(url.lastIndexOf(".") + 1);
//                                BufferedImage bufferImg = ImageIO.read(imgUrl);
//                                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
//                                ImageIO.write(bufferImg, suffix, byteArrayOut);
//                                XSSFClientAnchor anchor = new XSSFClientAnchor(1, 1, 1, 1, 17, rowNum, 18, rowNum + 1);
//                                //插入图片
//                                drawing.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
//                            } catch (Exception e) {
//                                logger.error(e.getMessage(),e);
//                            }
//                        }
//                    }
//                    String rectificationAttachment = discovery.getRectificationAttachment();
//                    if (StringUtils.isNotEmpty(rectificationAttachment)) {
//                        List<String> list = JSONArray.parseArray(rectificationAttachment, String.class);
//                        String url = null;
//                        if (null != list && list.size() > 0) {
//                            // 如果有多张图片，则取第一张
//                            url = list.get(0).split("#")[0];
//                        }
//                        if (null != url) {
//                            // 对图片单独捕获异常
//                            try {
//                                URL imgUrl = new URL(url);
//                                String suffix = url.substring(url.lastIndexOf(".") + 1);
//                                BufferedImage bufferImg = ImageIO.read(imgUrl);
//                                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
//                                ImageIO.write(bufferImg, suffix, byteArrayOut);
//                                XSSFClientAnchor anchor = new XSSFClientAnchor(1, 1, 1, 1, 18, rowNum, 19, rowNum + 1);
//                                //插入图片
//                                drawing.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
//                            } catch (Exception e) {
//                                logger.error(e.getMessage(),e);
//                            }
//                        }
//                    }
                    row.setHeightInPoints(50);
                    index++;
                    rowNum++;
                }
            }
            return workbook;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public MessageBean<DataBean<HiddenDangerDiscovery>> homePageDangerList(StaffBean user, String corpCode, String
            gridCode, String checkUnit, Integer state, Date startTime, Date endTime, Integer start, Integer rows) {
        MessageBean<DataBean<HiddenDangerDiscovery>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<HiddenDangerDiscovery> list = new ArrayList<>();
            Integer totalNumber = 0;
            String codes = util.getCodes(corpCode);
            HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
            list = mapper.homePageList(corpCode, codes, checkUnit, state, startTime, endTime, start, rows);
            totalNumber = mapper.homePageListCount(corpCode, codes, checkUnit, state, startTime, endTime);
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = totalNumber > rows
                    ? totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1 : 1;
            DataBean<HiddenDangerDiscovery> dataBean = new DataBean<>();
            dataBean.setPageSize(rows);
            list.forEach(item -> getNames(item));
            dataBean.setList(list);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setData(dataBean);
            msg.setDescription("获取隐患列表成功");
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<String> withdrawWorkFlow(StaffBean user, String id) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "流程撤回成功", String.class);
        SessionFactory factory = null;
        try {
            if (StringUtils.isEmpty(id)) {
                return MessageBean.create(BusinessCode.FAILURE.getCode(), BusinessCode.FAILURE.getDescription(), String.class);
            }
            factory = new SessionFactory();
            HiddenDangerMapper dangerMapper = factory.getMapper(HiddenDangerMapper.class);
            AuditMapper auditMapper = factory.getMapper(AuditMapper.class);
            //获取隐患信息
            HiddenDangerDiscovery entity = dangerMapper.queryDangerOne(id);
            if (null != entity) {
                if (entity.getState() == 1 || entity.getState() == 2 || entity.getState() == 4) {
                    if (!entity.getSubmitterCode().contains(user.getCode()) && !user.getCode().equals("AE532A5299A74366AB97982F1B464E64")) {
                        return MessageBean.create(BusinessCode.FAILURE.getCode(), "只能由创建人撤回流程", String.class);
                    }
                } else {
                    //非管理员账号无法撤销操作其他的账号
                    if (!user.getCode().equals("AE532A5299A74366AB97982F1B464E64")) {
                        return MessageBean.create(BusinessCode.FAILURE.getCode(), "隐患非待整改状态，无法撤回", String.class);
                    }
                }
            }
            // 获取流程信息
            Audit audit = auditMapper.getAuditByBusinessId(id);
            if (null != audit) {
                List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
                if (null != idList && idList.size() > 0) {
                    // 将隐患信息回滚草稿
                    factory.getMapper(HiddenDangerMapper.class).updateDangerStateAndOperation(0, 0, idList);
                    //删除隐患相关得整改信息
                    dangerMapper.bateDeleteRectificationByDiscoveryId(idList);
                    // 隐患废弃后，删掉对应的隐患整改通知书信息
                    HiddenDangerRectificationServiceImpl.DeleteNotice(factory, idList);
                    // 获取所有的fe消息信息
//                    List<FeMessage> feMessages = auditMapper.queryAllFeMessageByBillId(audit.getId());
//                    // 更新fe消息状态
//                    if (null != feMessages && feMessages.size() > 0) {
//                        List<String> messageIds = feMessages.stream().map(s -> s.getMessageId()).collect(Collectors.toList());
//                        auditMapper.batchUpdateFeMessage(messageIds, 4);
//                       // messageIds.forEach(messageId -> SendFeMessage.updateMsg(messageId, "4"));
//                    }
                }
                //删除流程
                auditMapper.delete(audit.getId());
            } else {
                List<String> idList = new ArrayList() {{
                    this.add(id);
                }};
                // 将隐患信息回滚草稿
                factory.getMapper(HiddenDangerMapper.class).updateDangerStateAndOperation(0, 0, idList);
                //删除隐患相关得整改信息
                dangerMapper.bateDeleteRectification(idList);
                // 隐患废弃后，删掉对应的隐患整改通知书信息
                HiddenDangerRectificationServiceImpl.DeleteNotice(factory, idList);
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            if (factory != null)
                factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            return MessageBean.create(BusinessCode.EXCEPTION.getCode(), BusinessCode.EXCEPTION.getDescription(), String.class);
        } finally {
            if (factory != null)
                factory.close();
        }
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
        // 只有新启的隐患流程才做以下操作
        if (hiddenDangerWorkFlow.equals(audit.getTemplateKey())) {
            SessionFactory factory = null;
            StaffBean user = null;
            List<HiddenDangerDiscovery> dangerDiscoveryList = null;
            Boolean flag = true;
            Boolean delay = false;
            try {
                factory = new SessionFactory();
                //查询审批的节点流转到哪里
                MessageBean<?> history = flowService.history(audit.getSetCode(), audit.getTemplateKey(), audit.getId());
                String userId = null;
                String taskId = null;
                String nowNodeCode = null;
                if (0 == history.getCode() && history.getData() != null) {
                    List<Map> historys = (List<Map>) history.getData();
                    if (historys != null && historys.size() > 0) {
                        List<Map> tasks = (List<Map>) historys.get(historys.size() - 1).get("tasks");
                        if (tasks != null && tasks.size() > 0 && tasks.get(0) != null) {
                            userId = (String) tasks.get(0).get("user");
                            taskId = (String) tasks.get(0).get("taskId");
                            nowNodeCode = (String) tasks.get(0).get("taskCode");
                        }
                    }
                }
                if (StringUtils.isNotEmpty(userId)) {
                    List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userId, 2).getData();
                    user = staffBeanList.get(0);
                    //获取用户所在部门
                    List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(user.getCode()).getData();
                    if (null != deptBeanList) {
                        user.setDepartmentCode(deptBeanList.get(0).getCode());
                        user.setDepartmentname(deptBeanList.get(0).getName());
                        user.setDepartmentid(deptBeanList.get(0).getId());
                    }
                }
                List<String> idList = JSONArray.parseArray(audit.getBusinessIds(), String.class);
                if (null != idList && idList.size() > 0) {
                    dangerDiscoveryList = factory.getMapper(HiddenDangerMapper.class).queryDangerByIdList(idList);
                }
                if (operation == 2) {
                    if (null != dangerDiscoveryList && dangerDiscoveryList.size() > 0) {
                        for (HiddenDangerDiscovery discovery : dangerDiscoveryList) {
                            List<HiddenDangerRectification> rectificationList = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(discovery.getId());
                            if (null != rectificationList && rectificationList.size() > 0) {
                                HiddenDangerRectification rectification = rectificationList.get(0);
                                rectification.setRectifier(user.getCode() + "_" + user.getUserid());
                                rectification.setRectifierName(user.getName() + "_" + user.getDepartmentname());
                                factory.getMapper(HiddenDangerMapper.class).updateRectification(rectification);
                            }
                        }
                    }
                } else if (operation == 32 && ("Process-task3").equals(nowNodeCode)) {
                    if (null != dangerDiscoveryList && dangerDiscoveryList.size() > 0) {
                        // 判断是否有延期
                        for (HiddenDangerDiscovery discovery : dangerDiscoveryList) {
                            List<HiddenDangerRectification> rectificationList = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(discovery.getId());
                            if (null != rectificationList && rectificationList.size() > 0) {
                                HiddenDangerRectification rectification = rectificationList.get(0);
                                if (rectification.getDelayState() == 1) {
                                    flag = false;
                                    delay = true;
                                    break;
                                }
                            }
                        }
                        // 检查整改人和负责人是否为同一人
                        if (flag) {
                            for (HiddenDangerDiscovery discovery : dangerDiscoveryList) {
                                List<HiddenDangerRectification> rectificationList = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(discovery.getId());
                                if (null != rectificationList && rectificationList.size() > 0) {
                                    HiddenDangerRectification rectification = rectificationList.get(0);
                                    if (!discovery.getDangerManager().equals(rectification.getRectifier())) {
                                        flag = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    //没有延期，且检查整改人和负责人为同一人，跳过验证环节
                    if (flag) {
                        MessageBean<?> msg = flowService.submit(audit.getSetCode(), audit.getTemplateKey(), audit.getId(), userId, taskId, null, "自动跳过", operation, null, null, null, null, null);
                        if (msg.getCode() == BusinessCode.SUCCESS.getCode()) {
                            audit.setNowNodeCode("Process-task4");
                            factory.getMapper(AuditMapper.class).update(audit);
                            for (HiddenDangerDiscovery discovery : dangerDiscoveryList) {
                                List<HiddenDangerRectification> rectificationList = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(discovery.getId());
                                if (null != rectificationList && rectificationList.size() > 0) {
                                    HiddenDangerRectification rectification = rectificationList.get(0);
                                    rectification.setReviewState(1);
                                    discovery.setState(6);
                                    discovery.setOperation(5);
                                    factory.getMapper(HiddenDangerMapper.class).updateDanger(discovery);
                                    factory.getMapper(HiddenDangerMapper.class).updateRectification(rectification);
                                }
                            }
                        }
                    }
                    // 如果有延期，修改隐患验证人为下发人
                    if (delay) {
                        if (null != dangerDiscoveryList && dangerDiscoveryList.size() > 0) {
                            for (HiddenDangerDiscovery discovery : dangerDiscoveryList) {
                                List<HiddenDangerRectification> rectificationList = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(discovery.getId());
                                if (null != rectificationList && rectificationList.size() > 0) {
                                    HiddenDangerRectification rectification = rectificationList.get(0);
                                    rectification.setReviewer(user.getCode());
                                    rectification.setReviewerName(user.getName());
                                    factory.getMapper(HiddenDangerMapper.class).updateRectification(rectification);
                                }
                            }
                        }
                    } else {
                        if (null != dangerDiscoveryList && dangerDiscoveryList.size() > 0) {
                            for (HiddenDangerDiscovery discovery : dangerDiscoveryList) {
                                List<HiddenDangerRectification> rectificationList = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(discovery.getId());
                                if (null != rectificationList && rectificationList.size() > 0) {
                                    HiddenDangerRectification rectification = rectificationList.get(0);
                                    if (!rectification.getReviewer().equals(discovery.getDangerManager().split("_")[0])) {
                                        List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(discovery.getDangerManager().split("_")[0], null).getData();
                                        List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(discovery.getDangerManager().split("_")[0]).getData();
                                        if (staffBeanList.size() <= 0 || null == staffBeanList || null == deptBeanList || deptBeanList.size() <= 0) {
                                            factory.close(false);
                                        }
                                        rectification.setReviewer(discovery.getDangerManager().split("_")[0]);
                                        rectification.setReviewerName(staffBeanList.get(0).getName() + "_" + deptBeanList.get(0).getName());
                                        factory.getMapper(HiddenDangerMapper.class).updateRectification(rectification);
                                    }
                                }
                            }
                        }
                    }
                    for (HiddenDangerDiscovery discovery : dangerDiscoveryList) {
                        String managerWxUserId = null;
                        List<StaffBean> list = (List<StaffBean>) util.staff(discovery.getDangerManager().split("_")[0], null).getData();
                        if (null != list && list.size() > 0) {
                            managerWxUserId = list.get(0).getOpenid();
                        }
                        if (StringUtils.isNotEmpty(managerWxUserId)) {
                            StringBuffer sb = new StringBuffer();
                            sb.append("温馨提示:\n现有一条您负责的隐患整改单已完成整改，请验收\n单号：").append(audit.getCode()).append("\n标题：").append(audit.getTitle()).append("\n发起人：")
                                    .append(audit.getAddUser()).append("\n请进入安全管理信息系统待办处理,如已处理,请忽略本消息\n<a href=\"")
                                    .append("/redirectoauth.htm\">点击进入系统</a>");
                            ;
                            // 发送企业微信消息
                            //SendWxMessage.sendMsg(managerWxUserId, null, null, sb.toString());
                        }
                    }
                }
                factory.close();
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
                if (null != factory) {
                    factory.close(false);
                }
                logger.error(e.getMessage(),e);
            }
        }
    }

    public void analyseHiddenDangerDiscovery(MessageBean<List<HiddenDangerDiscovery>> messageBean, MessageBean<DataBean<HiddenDangerDiscovery>> msg) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        if (msg.getCode() == BusinessCode.SUCCESS.getCode()) {
            List<HiddenDangerDiscovery> list = msg.getData().getList();
            if (null != list && list.size() > 0) {
                for (HiddenDangerDiscovery discovery : list) {
                    try (SessionFactory factory = new SessionFactory()) {
                        if (null != discovery.getDiscoveryTime()) {
                            String discoveryTimeStr = format.format(discovery.getDiscoveryTime());
                            discovery.setDiscoveryTimeStr(discoveryTimeStr);
                        }
                        if (null != discovery.getDeadline()) {
                            String deadlineStr = format.format(discovery.getDeadline());
                            discovery.setDeadlineStr(deadlineStr);
                        }
                        if (StringUtils.isNotEmpty(discovery.getDiscovererDepartment())) {
                            discovery.setDiscovererDepartment(JSONArray.parseArray(discovery.getDiscovererDepartment(), String.class).stream().collect(Collectors.joining(",")));
                        }
                        if (StringUtils.isEmpty(discovery.getNoticeCode())) {
                            String noticeCode = factory.getMapper(HiddenDangerRectificationMapper.class).getNoticeCode(discovery.getId());
                            discovery.setNoticeCode(noticeCode);
                        }
                        if (StringUtils.isNotEmpty(discovery.getRectifier())) {
                            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(discovery.getRectifier().split("_")[0], null).getData();
                            if (null != staffBeanList && staffBeanList.size() > 0) {
                                String mobile = staffBeanList.get(0).getMobile();
                                discovery.setRectifierTel(mobile);
                                if (StringUtils.isNotEmpty(discovery.getReviewerName())) {
                                    String[] reviewers = discovery.getReviewerName().split("_");
                                    String name = "";
                                    String unit = "";
                                    name = reviewers[0];
                                    if (reviewers.length > 1) {
                                        unit = reviewers[1];
                                    } else {
                                        List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(discovery.getReviewer()).getData();
                                        if (null != deptBeanList && deptBeanList.size() > 0) {
                                            unit = deptBeanList.get(0).getName();
                                        }
                                    }
                                    discovery.setRectifierUnit(unit);
                                    discovery.setReviewerName(name);
                                }
                            }
                        }
                    }
                }
            }
            messageBean.setData(list);
        }
        messageBean.setCode(BusinessCode.SUCCESS.getCode());
        messageBean.setDescription(BusinessCode.SUCCESS.getDescription());
    }
}
